#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <queue>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
#include "serv_network.h"

using namespace std;

Network network;

// Send a packet to a client
void ThreadSendingFunc(void* UserData)
{
    while(1)
    {
		sf::Sleep(0.001f);

		network.SendPackets();
    }
}

// When you receive a packet from a client
void ThreadReceivingFunc(void* UserData)
{
    while(1)
    {
		sf::Sleep(0.001f);

		network.ReceivePackets();
    }
}

// Commands of the server console
void ThreadCommandFunc(void* UserData)
{
    string commandFunction;
    while (1)
    {
        cin >> commandFunction;
        if (commandFunction == "stop")
            network.SetStatus(false);
    }
}

// Ping all clients every 20 seconds
void ThreadPingFunc(void* UserData)
{
	while (1)
	{
		sf::Sleep(20.0f);

		network.Ping();
	}
}

int main(int argc, const char **argv)
{
	// Connect to the database and listen for TCP clients
	network.Connect();

	// Launch the threads
    sf::Thread Thread(&ThreadSendingFunc);
    Thread.Launch();

    sf::Thread Thread2(&ThreadReceivingFunc);
    Thread2.Launch();

    sf::Thread Thread3(&ThreadCommandFunc);
    Thread3.Launch();

	sf::Thread Thread4(&ThreadPingFunc);
    Thread4.Launch();

	// Main loop
    while (network.status())
    {
		network.Refresh();
    }

	// Close the network
    network.Close();

	// Close the threads
    Thread.Terminate();
    Thread2.Terminate();
    Thread3.Terminate();
	Thread4.Terminate();

    return 0;
}
